#include "pinctrl.h"
#include "uart.h"
#include "osal_debug.h"
#include "soc_osal.h"
#include "app_init.h"
#include "string.h"
#include "cmsis_os2.h"
#include "pinctrl.h"
#include "gpio.h"
#include "soc_osal.h"
#include "app_init.h"
#include "cmsis_os2.h"
#include "platform_core_rom.h"
#include "UART1.h"


#define DELAY_TIME_MS 1
#define UART_RECV_SIZE 10

uint8_t uart_recv[UART_RECV_SIZE] = {0};

uint8_t voice_Cmd; 

#define UART_INT_MODE 1
#if (UART_INT_MODE)

#endif
uart_buffer_config_t g_app_uart_buffer_config = {.rx_buffer = uart_recv, .rx_buffer_size = UART_RECV_SIZE};
// 初始化 UART 引脚
void uart_gpio_init(void)
{

    uapi_pin_set_mode(uart1_txt , PIN_MODE_1);
    uapi_pin_set_mode(uart1_rxt, PIN_MODE_1);

/*
    uapi_pin_set_mode(GPIO_17, PIN_MODE_1);
    uapi_pin_set_mode(GPIO_18, PIN_MODE_1);
    */
}
// 初始化 UART 配置
void uart_init_config(void)
{
    // 定义一个 uart_attr_t 类型的结构体变量 attr，用于存储 UART 的属性
    uart_attr_t attr = {
        .baud_rate = 115200, .data_bits = UART_DATA_BIT_8, .stop_bits = UART_STOP_BIT_1, .parity = UART_PARITY_NONE};

    uart_pin_config_t pin_config = {.tx_pin = uart1_txt, .rx_pin =uart1_rxt, .cts_pin = PIN_NONE, .rts_pin = PIN_NONE};
    uapi_uart_deinit(uart_id);
    int ret = uapi_uart_init(uart_id, &pin_config, &attr, NULL, &g_app_uart_buffer_config);
    if (ret != 0) {
        printf("uart init failed ret = %02x\n", ret);
    }
}

#if (UART_INT_MODE)
void uart_read_handler(const void *buffer, uint16_t length, bool error)
{
    unused(error);
    int found = 0;  // 标志位，用于判断是否找到匹配值
    if (buffer == NULL || length == 0) {
        return;
    }
    if (memcpy_s(uart_recv, length, buffer, length) != EOK) {
        return;
    }
    //当 UART 通过中断接收到数据时，硬件会触发回调函数 uart_read_handler。该函数将接收到的数据复制到缓冲区 uart_recv 

    for (int i = 0; i < length; i++) {
    switch (uart_recv[i]) {
        case 0x01:
            voice_Cmd = 1;//收到右转指令
            found = 1;
            break;
        case 0x02:
            voice_Cmd = 2;//收到左转指令
            found = 1;
            break;
        case 0x05:
            voice_Cmd = 3;//收到电话指令
            found = 1;
            break;
        case 0x06:
            voice_Cmd = 4;//收到双闪指令
            found = 1;
            break;
        case 0x07:
            voice_Cmd = 5;//收到投影指令
            found = 1;
            break;
        default:
            break;  // 无匹配时继续循环
    }
    if (found) {
        break;  // 找到匹配后立即退出循环
    }
}

    for (int i = 0; i < UART_RECV_SIZE; i++) {
        printf("%02X ", uart_recv[i]); // %02X 表示2位十六进制
    }

    
        memset(uart_recv, 0, UART_RECV_SIZE);//清除数组

}
#endif


void uart1_init(void)
{
    uart_gpio_init();
    uart_init_config();
    uapi_uart_register_rx_callback(1, UART_RX_CONDITION_MASK_IDLE, 1, uart_read_handler);
}

